package com.smartlight.godlight;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.smartlight.godlight.constant.GodlApi;
import com.smartlight.godlight.model.OrderInfo;
import com.smartlight.godlight.utils.OkHttpUtils;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class ScanPay extends AppCompatActivity {
    private String TAG = "ScanPay";
    private OrderInfo orderInfo;

    @Override
    protected void  onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.scanpay);

        // toolbar
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        // 获取ActionBar对象（实际上是Toolbar）并设置属性
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(true); // 显示返回箭头
            actionBar.setHomeAsUpIndicator(R.drawable.arrow_yellow); // 设置返回图标
            actionBar.setTitle("返回"); // 设置标题文字
        }

        Button btn_payfinish = findViewById(R.id.submitorder);

        // 获取参数
        Intent intent = getIntent();
        orderInfo = intent.getParcelableExtra("orderInfo");
        Log.d(TAG, "传过来的订单独享----" + orderInfo.toString());

        // 刷新UI
        TextView editname = findViewById(R.id.editname);
        TextView editphone = findViewById(R.id.editphone);
        TextView buddhaNo = findViewById(R.id.buddhaNo);
        TextView editblessing = findViewById(R.id.editblessing);
        TextView edittimespan = findViewById(R.id.edittimespan);
        TextView moneyTextview = findViewById(R.id.moneyTextview);

        editname.setText(orderInfo.getName());
        editphone.setText(orderInfo.getPhone());
        buddhaNo.setText(orderInfo.getBuddhaName() + "  " + orderInfo.getBuddhaNo() + "号佛灯");
        editblessing.setText(orderInfo.getBlessing());
        edittimespan.setText(orderInfo.getTimespanName());
        moneyTextview.setText("￥" + orderInfo.getMoney() + "元");

        // 请求订单号
        OkHttpUtils.get(GodlApi.GET_MerOrderId, new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {

            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                String result = response.body().string();
                JsonObject jsonObject = new Gson().fromJson(result, JsonObject.class);
                String orderNo = jsonObject.get("data").getAsJsonObject().get("merOrderId").getAsString();
                orderInfo.setOrderNo(orderNo);

                Log.d(TAG, orderInfo.toString());
            }
        });

        btn_payfinish.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Map<String, String> params = new HashMap<>();
                params.put("order_no", orderInfo.getOrderNo());             // 订单号
                params.put("username", orderInfo.getName());                // 用户名
                params.put("phone", orderInfo.getPhone());                  // 手机号
                params.put("buddha_name", orderInfo.getBuddhaName());       // 佛像名称
                params.put("buddha_no", orderInfo.getBuddhaNo());           // 佛灯号码
                params.put("blessing", orderInfo.getBlessing());            // 祈福语
                params.put("timespan_title", orderInfo.getTimespanName());  // 时长名称
                params.put("timespan", orderInfo.getMonth() + "");          // 时长长度
                params.put("start_time", "");                             // 开始时间
                params.put("end_time", "");                               // 结束时间
                params.put("currency", "");                               // 货币
                params.put("money", orderInfo.getMoney() + "");             // 金额

                Log.d(TAG, params.toString());

                // 调用提交订单接口，用于数据记录
                OkHttpUtils.post(GodlApi.SUBMIT_ORDER, params, new Callback() {
                    @Override
                    public void onFailure(@NonNull Call call, @NonNull IOException e) {
                        GodlApi.printLog(TAG, "接口:" + GodlApi.GET_APP_INFO + ", 请求失败, " + e.toString());
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(ScanPay.this, "订单提交失败，请重新提交或寻求管理人员帮忙。", Toast.LENGTH_SHORT).show();
                            }
                        });
                    }

                    @Override
                    public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                        String data = response.body().string();

                        try {
                            JsonObject jsonObject = new Gson().fromJson(data, JsonObject.class);
                            if (jsonObject.get("code").getAsInt() == 0){
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        Toast.makeText(ScanPay.this, jsonObject.get("msg").getAsString(), Toast.LENGTH_LONG).show();
                                    }
                                });
                                return;
                            }

                            JsonObject infoObj = jsonObject.get("data").getAsJsonObject();

                            orderInfo.setStartTime(infoObj.get("start_time").getAsLong());
                            orderInfo.setEndTime(infoObj.get("end_time").getAsLong());

                            // 跳转到支付页面
                            Intent intent = new Intent();
                            intent.setClass(ScanPay.this,Payment.class);
                            intent.putExtra("orderInfo", orderInfo);
                            startActivity(intent);
                        }
                        catch (Exception e){
                            // 接口返回数据异常处理
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(ScanPay.this, "数据返回异常，请返回重新填写，或联系工作人员。", Toast.LENGTH_LONG).show();
                                }
                            });
                        }
                    }
                });

            }
        });

    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                // 返回按钮被点击时执行的代码
                Toast.makeText(this, "返回按钮被点击", Toast.LENGTH_SHORT).show();
                finish();
                return true; // 表示事件已被处理，不再向上传递
        }
        return super.onOptionsItemSelected(item); // 对于其他菜单项，调用父类的处理方法
    }

}
